package com.lfs.dingtalk.robot.servcie;

import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOHeaders;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTORequest;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.lfs.dingtalk.robot.constants.CommonConstant;
import com.lfs.dingtalk.robot.domain.MsgParam;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import shade.com.alibaba.fastjson2.JSON;

import java.util.Collections;

@Service
@Slf4j
public class DingtalkSendService {




    /**
     * 单发(20一批)
     */
    public String sendToUser(String msgKey, MsgParam msgParam) {
        com.aliyun.dingtalkrobot_1_0.Client client = createClient();
        BatchSendOTOHeaders batchSendOTOHeaders = new BatchSendOTOHeaders();
        batchSendOTOHeaders.xAcsDingtalkAccessToken = DingTalkService.getAccessToken();
        BatchSendOTORequest batchSendOTORequest = new BatchSendOTORequest()
                .setRobotCode(CommonConstant.APP_KEY)
                .setUserIds(Collections.singletonList("02500732495021689248"))  //useId实际上在这个位置看：https://oa.dingtalk.com/contacts.htm#/contacts
                .setMsgKey(msgKey)
                .setMsgParam(JSON.toJSONString(msgParam));
        try {
            BatchSendOTOResponse batchSendOTOResponse = client.batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new RuntimeOptions());
            return batchSendOTOResponse.getBody().getProcessQueryKey();
        } catch (Exception err) {
            log.error("普通卡片发送失败", err);
        }
        return null;
    }


    /**
     * 使用 Token 初始化账号Client
     * @return Client
     */
    @SneakyThrows
    public static com.aliyun.dingtalkrobot_1_0.Client createClient() {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkrobot_1_0.Client(config);
    }

}
